package com.pignest.hotel.ui.reception;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listhead;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;


import com.pignest.framework.util.DateUtils;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.Memberchargehistrory;
import com.pignest.hotel.beans.Room;
import com.pignest.hotel.beans.TbAccounts;
import com.pignest.hotel.beans.TbCloseAccounts;
import com.pignest.hotel.beans.TbLiveGoodsBorrow;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.definition.InComeItemType;
import com.pignest.hotel.definition.LivingState;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.module.user.ui.ModelListHead;
import com.pignest.hotel.service.CardService;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.service.RoomService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class CheckOutWindow extends Window implements EventListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 227391272365009917L;

	private ReceptionService receptionService;
	private MemberService memberService;
	private CardService cardService;
	private RoomService roomService;
	private Room room;
	public Living living;
	private boolean success;//业务是否成功完成
	
	private Textbox roomNameTextbox;			//房间名
	private Textbox livingTypeTextbox;
	private Textbox relativeRoomTextbox;		//关联的房间号, 团队, 联房
	private Textbox customNameTextbox;
	private Textbox sexListbox;
	private Textbox phoneTextbox;
	private Textbox otherContactTextbox;
	private Textbox passportTypeListbox;
	private Textbox passportNunberTextbox;
	private Textbox memberTextbox;
    private Textbox memberLevelText;
	private Textbox roomPriceTextbox;
	private Textbox adjustPriceTextbox;
	private Textbox leaveDate;
	private Textbox liveTime;
	private Textbox storageTextbox;
	private Textbox usedTextbox;
	private Textbox balanceTextbox;
	private Listbox paymentMethodListbox;
	private Listbox invoiceListbox;
	//private Textbox cardNumberTextbox;
	private Textbox remarkTextbox;
	
	//private Toolbarbutton addHalfDaybtn;
	//private Toolbarbutton addFullDaybtn;
	//private Radio halfDay;
	//private Radio fullDay;
	//private Radio cancelAdd;
	private Radiogroup addGroup;
	
	private Toolbarbutton goodBorrowBtn;
	
	private Listbox checkoutListbox;
	public CheckOutWindow() {
		receptionService = Services.getReceptionService();
		memberService= Services.getMemberService();
		cardService =Services.getCardService();
		roomService =Services.getRoomService();
		addEventListener("onCreate", this);
	}
	@Override
	public void onEvent(Event event) throws Exception {
		// TODO Auto-generated method stub
		if ("onCreate".equals(event.getName())) {
			roomNameTextbox = (Textbox) getFellow("roomName");
			livingTypeTextbox = (Textbox) getFellow("livingType");
			relativeRoomTextbox = (Textbox) getFellow("relativeRoom");
			customNameTextbox = (Textbox) getFellow("customName");
			sexListbox = (Textbox) getFellow("gender");
			phoneTextbox = (Textbox) getFellow("phone");
			otherContactTextbox = (Textbox) getFellow("otherContact");
			passportTypeListbox = (Textbox) getFellow("passportType");
			passportNunberTextbox = (Textbox) getFellow("passportNumber");
			memberTextbox = (Textbox) getFellow("member");
			memberLevelText =(Textbox) getFellow("memberLevel");
			roomPriceTextbox = (Textbox) getFellow("roomPrice");
			adjustPriceTextbox = (Textbox) getFellow("adjustPrice");
			leaveDate = (Textbox) getFellow("leaveDate");
			liveTime = (Textbox) getFellow("liveTime");
			paymentMethodListbox = (Listbox) getFellow("paymentMethod");
			invoiceListbox = (Listbox) getFellow("invoiceListbox");
			//cardNumberTextbox = (Textbox) getFellow("cardNumber");
			remarkTextbox = (Textbox)getFellow("remark");
			storageTextbox =(Textbox)getFellow("storage");
			usedTextbox =(Textbox)getFellow("used");
			balanceTextbox =(Textbox)getFellow("balance");
			roomNameTextbox.setValue(room.getName());
			checkoutListbox=(Listbox)getFellow("checkoutListbox");
			goodBorrowBtn=(Toolbarbutton)getFellow("goodBorrowBtn");
			
		//	addHalfDaybtn=(Toolbarbutton)getFellow("addHalfDaybtn");
		//	addFullDaybtn=(Toolbarbutton)getFellow("addFullDaybtn");
			//halfDay= (Radio)getFellow("halfDay");
			//fullDay=(Radio)getFellow("halfDay");
			//cancelAdd=(Radio)getFellow("cancelAdd");
			addGroup =(Radiogroup)getFellow("addGroup");
			Living l= (Living)receptionService.getLiving(room);
			this.living=l;
			String memberName="";
			String memberLevel="";
			System.out.println("name:"+l.getCustormName());
			if(l.getMember()!=null){
				
				memberName=l.getMember().getName();
				if(l.getMember().getMemberLevel()!=null)
				  memberLevel=l.getMember().getMemberLevel().getMemberlevel();
				memberTextbox.setValue(memberName);
				memberLevelText.setValue(memberLevel);
			}
			livingTypeTextbox.setValue(l.getLiveType());
			customNameTextbox.setValue(l.getCustormName());
			sexListbox.setValue(l.getSex());
			phoneTextbox.setValue(l.getPhone());
			passportTypeListbox.setValue(l.getPassportType());
			passportNunberTextbox.setValue(l.getPassportNumber());
			adjustPriceTextbox.setValue(MoneyUtil.toString(l.getAdjustPrice()));
			liveTime.setValue(DateUtils.toString(l.getLiveTime(), DateUtils.DEFAULT_DATETIME_FORMAT));//入住时间
			leaveDate.setValue(DateUtils.currentDateToString(DateUtils.DEFAULT_DATETIME_FORMAT));
			roomPriceTextbox.setValue(MoneyUtil.toString(l.getRoomPrice()));
			storageTextbox.setValue(MoneyUtil.toString(l.getStorage()));
			flush();
		}
	}
	/**
	 * 操作完成相关业务后调用
	 * */
	public void flush(){
		calculate(this.living);
		this.checkoutListbox.getItems().clear();
		queryAccounts();
		isGoodBorrow();
		//isDisabledOrNot();
		//根据时间判断是否要加收房费
		isAddInCome(this.living);
	}
	public void queryAccounts(){
		checkoutListbox.getItems().clear();
		StringBuffer hql=new StringBuffer();
	       if(this.living!=null)
			  hql.append(" from TbAccounts b where b.living.id='"+this.living.getId()+"'");
		    List <TbAccounts> atList=receptionService.find(hql.toString());
		    for(TbAccounts s:atList){
		    	Listitem listitem = new Listitem();
		    	listitem.setParent(checkoutListbox);
		    	listitem.setValue(s.getId());
		    	listitem.appendChild(new Listcell(s.getName()));
		    	//listitem.appendChild(new Listcell(s.getType()));
		    	listitem.appendChild(new Listcell(MoneyUtil.toString(s.getPrice())));
		    	/*Integer i =s.getCounts();
		    	if(i!=null)*/
		    		listitem.appendChild(new Listcell(String.valueOf(s.getCounts())));
		    	/*else
		    		listitem.appendChild(new Listcell(""));*/
		    	
		    	listitem.appendChild(new Listcell(MoneyUtil.toString(s.getPrice2())));
		    	listitem.appendChild(new Listcell(s.getEndstate()));
		    	//listitem.appendChild(new Listcell(DateUtil.toString(s.getOptime())));
		    	listitem.appendChild(new Listcell(s.getOpdate()));
		    }
	}
	public void queryBorrowGoods(String livingId ){
		StringBuffer hql=new StringBuffer();
       if(livingId!=null)
		  hql.append(" from TbLiveGoodsBorrow b where b.living.id='"+livingId+"'");
	    List <TbLiveGoodsBorrow> goodsBorrowList=receptionService.find(hql.toString());
	    for(TbLiveGoodsBorrow s:goodsBorrowList){
	    	Listitem listitem = new Listitem();
	    	listitem.setValue(s.getId());
	    	listitem.setParent(checkoutListbox);
	    	listitem.appendChild(new Listcell(s.getTbGoods().getName()));
	    	listitem.appendChild(new Listcell(DateUtil.toString(s.getTime())));
	    	listitem.appendChild(new Listcell(DateUtil.toString(s.getBacktime())));
	    	Integer i=s.getCount();
	    	if(i!=null)
	    	   listitem.appendChild(new Listcell(String.valueOf(s.getCount())));
	    	else
	    		listitem.appendChild(new Listcell(""));
	    }
	   
	}

	public void setRoom(Room room) {
		this.room = room;
	}
	
	public Room getRoom() {
		return room;
	}
	public String addHalfDay(){
		if(this.living!=null){
			TbAccounts ts = new TbAccounts();
			ts.setLiving(living);
			//ts.setType("加收房费");
			ts.setType(InComeItemType.JSFF.name());
			ts.setCounts(1);
			ts.setName("半天房费");
			//ts.setName(InComeItemType.JSFF.getValue());
			String s=adjustPriceTextbox.getValue();
			//4舍5入取整
			double ad=Double.valueOf(s);
			int price=MoneyUtil.rand(ad*0.5);
			
			ts.setPrice(-MoneyUtil.dollar2cent(price));

            ts.setEndstate("否");
            ts.setOptime(new Date());
            ts.setPrice2(MoneyUtil.dollar2cent(MoneyUtil.rand(ad)));
            ts.setRemark("加收半天房费");
            //receptionService.insert(ts);
           // this.living=receptionService.addDayPay(this.living, ts);

            flush();
            return "";

		}else{
			return "无效的入住";
		}
	}
	public String addOneDay(){
		if(this.living!=null){
			TbAccounts ts = new TbAccounts();
			ts.setLiving(living);
			//ts.setType("加收房费");
			ts.setType(InComeItemType.JSFF.name());
			ts.setCounts(1);
			ts.setName("一天房费");
			String s=adjustPriceTextbox.getValue();
			//4舍5入取整
			double ad=Double.valueOf(s);
			int price=MoneyUtil.rand(ad);
			
			ts.setPrice(MoneyUtil.dollar2cent(price));

            ts.setEndstate("否");
            ts.setOptime(new Date());
            ts.setPrice2(MoneyUtil.dollar2cent(MoneyUtil.rand(ad)));
            ts.setRemark("加收1天房费");
            receptionService.addDayPay(this.living, ts);
            flush();
            return "";

		}else{
			return "无效的入住";
		}
	}
	/**
	 * 退房结账
	 * 
	 * **/
	public String checkOut(Card card){
	try{
		boolean isCheckOut=receptionService.isCheckOut(this.living);
		if(isCheckOut)
		{
			this.success=false;
			return "已经结账了";
		}
		
		
		PayMethod payMethod=UIUtils.getSelectedValue(this.paymentMethodListbox);
		int invoice=Integer.valueOf((String)UIUtils.getSelectedValue(invoiceListbox));
		//重新计算一次免
		calculate(this.living);
		//设置离开时间
		this.living.setLeaveDate(new Date());
		this.living.setLiveState(LivingState.CHECKOUT.name());
		Double used =Double.valueOf(this.usedTextbox.getValue());
		int available =this.living.getAvailable();
		int allPrice=MoneyUtil.dollar2cent(used);
		StringBuffer msg = new StringBuffer();
			msg.append("你好：").append(living.getCustormName()).append("\n");
			//boolean isPayMethodMember=false;//是否用会员卡支付押金
		if(payMethod.name().equals(PayMethod.MEMBER_CARD.name()))
		{
			if(living.getMember()==null)
			{
				return "当前入住不是会员不能用会员卡结账！";
			}
			int balance= memberService.queryMemberBalance(living.getMember());
			int lost =balance-allPrice;
			if(lost<=0){
			   return "会员余额不足"+MoneyUtil.toString(lost)+"！请及时充值或者用现金结账！谢谢";
			}
				
	    }
		String s =addGroup.getSelectedItem().getValue();
		int price=0;
		TbAccounts ts = new TbAccounts();
		if(!s.equals("0")){		
		   ts.setLiving(living);
		   ts.setType(InComeItemType.JSFF.name());
		   ts.setCounts(1);
		   String s1=adjustPriceTextbox.getValue();
		   double ad=Double.valueOf(s1);
		   if(s.equals("0.5"))
		   {
			  ts.setName("半天房费");
			  price=MoneyUtil.rand(ad*0.5);
			  ts.setPrice(-MoneyUtil.dollar2cent(price));
			  ts.setRemark("加收半天房费");
			  msg.append("加收半天房费：").append(price).append("\n");
			}
			else{
				ts.setName("一天房费");
			    price=MoneyUtil.rand(ad);
			    ts.setPrice(-MoneyUtil.dollar2cent(price));
			    ts.setRemark("加收1天房费");
				msg.append("加收1天房费：").append(price).append("\n");
			}
            ts.setEndstate("否");
            ts.setOpdate(DateUtil.curDateStr());
	        ts.setOptime(new Date());
	        ts.setPrice2(MoneyUtil.dollar2cent(MoneyUtil.rand(ad)));
	    }
		//处理加收部分的金额
			used =used +price;
			available=living.getStorage()-MoneyUtil.dollar2cent(MoneyUtil.rand(used));
			this.living.setAvailable(available);
			TbCloseAccounts ca = new TbCloseAccounts();
			ca.setLiving(this.living);
			ca.setInvoice(invoice);
			ca.setTime(new Date());
			ca.setAccounts(MoneyUtil.dollar2cent(MoneyUtil.rand(used)));
			ca.setType(payMethod.name());
			User user =Hotel.getCurrentUser();
			ca.setUsername(user.getName());
			ca.setUserId(user.getId());
			
			//会员加收时增加记录
			Memberchargehistrory mch =null;
			if(payMethod.name().equals(PayMethod.MEMBER_CARD.name())){
				mch = new Memberchargehistrory();
				mch.setMember(living.getMember());
				mch.setChargeTime(new Date());
				mch.setPrice(-MoneyUtil.dollar2cent(MoneyUtil.rand(used)));
				mch.setChargetype("非自助");
				mch.setOptype(ChargeOpType.OnConsume.name());
				mch.setRemark(DateUtil.curDateStr()+ChargeOpType.OnCharge.getValue()+this.usedTextbox.getValue());
			}
			msg.append("当前结账方式：").append(payMethod.getDisplayName()).append("\n");
			msg.append("已消费：").append(used).append("\n");
			msg.append("余额").append(MoneyUtil.cent2dollar(available));
			if(UIUtils.confirm(msg.toString())){
				this.living.setLiveState(LivingState.CHECKOUT.name());
				boolean is=receptionService.updateCheckOut(this.living,ts,ca, room, mch,card);
				this.success=is;
				if(is)
					return null;
				else
					return "结账失败";
	
			}else{
				return "取消";
			}
		}catch(Exception e){
			e.printStackTrace();
			this.success=false;
			return "异常:"+e.getMessage();
		}
	}
	
	/**
	 * 计算消费
	 */
    public int calculateConsumption(String livingId){
    	StringBuffer hql=new StringBuffer();
    	int i=0;
    	
    	  hql.append("select sum(price) from TbAccounts b where b.living.id='"+livingId+"'");
  	   List o=receptionService.find(hql.toString());
  	   if(o!=null&&o.size()!=0){
  		  Object s= o.get(0);
  		  if(s!=null)
  		   i=Integer.valueOf(s.toString());
  	   }
  	   return i;
    }
    /**
     * 是否有加收半天或者一天的房费
     * @return
     */
    public boolean isAdd(){
    	if(this.living==null){
    		return false;
    	}
    	StringBuffer hql=new StringBuffer();
    	 hql.append(" from TbAccounts b where b.living.id='"+this.living.getId()+"'");
    	 hql.append(" and b.type='").append(InComeItemType.JSFF.name()).append("'");
    	   List o=receptionService.find(hql.toString());
    	   if(o!=null&&o.size()>=1){
    		 return true;
    	   }
    	   else{
    		   return false;
    	   }
    }
    /****
     * 计算消费情况
     */
    public void calculate(Living l){
    	l=receptionService.updateCalculate(l);
		balanceTextbox.setValue(MoneyUtil.toString(l.getAvailable()));
		usedTextbox.setValue(MoneyUtil.toString(l.getUsed()));
    }
    public void isGoodBorrow(){
    	boolean isback =receptionService.isGoodsBack(this.living);
    	if(isback)
    		 goodBorrowBtn.setLabel("有物品未归还请核实！");
    	else
    		goodBorrowBtn.setLabel("没有物品未归还");
    	
    }
    public String deleteProjects(){
    	try{
    	String [] ids =UIUtils.getSeclectListId(checkoutListbox);
    	//this.living=receptionService.deleteProjects(ids,this.living);
    	//calculate(this.living);
    	flush();
    	return "";
    	}catch(Exception e){
    		e.printStackTrace();
    		return "异常"+e.getMessage();
    	}
    }
    public boolean isSuccess() {
		return success;
	}
    
    public void isDisabledOrNot(){
    	if(isAdd()){
			//addHalfDaybtn.setDisabled(true);
			//addFullDaybtn.setDisabled(true);
		}else{
			//addHalfDaybtn.setDisabled(false);
			//addFullDaybtn.setDisabled(false);
		}
    }
    public void isAddInCome(Living l)
    {
    	Date liveTime =l.getLiveTime();
    	String sCurTime =DateUtil.currentDateToString(DateUtil.DEFAULT_DATETIME_FORMAT);
		String sLiveTime =DateUtil.toString(liveTime, DateUtil.DEFAULT_DATETIME_FORMAT);
		Double days =DateUtil.parseLiveDays(sLiveTime, sCurTime);
		System.out.println("days:"+days);
		if(days==0)
		{
			addGroup.getItemAtIndex(2).setChecked(true);
		}else if(days==0.5){
			addGroup.getItemAtIndex(0).setChecked(true);
		}else{
			addGroup.getItemAtIndex(1).setChecked(true);
			/*halfDay.setChecked(false);
			cancelAdd.setChecked(false);
			fullDay.setChecked(true);*/
		}
    }
    public String checkCard(Card card)
    {
    	if(card==null)
		{
			return "无效卡！";
		}
		if(card.getLockNumber()==null)
			return "系统检测无对应锁号！请确认！";
		Room r = roomService.getRoomByLock(card.getLockNumber());
		if(r==null)
		{
			return "此卡无对应房间！";
		}else
		{
			if(!r.getName().equals(living.getRoom().getName())){
				return "此卡解锁与房间不对应！";
			}
			
		}
		return null;
    }
 
}
